package com.ymtms.settlement.controller;

import com.ymtms.settlement.pojo.CollectingMoneyBalance;
import com.ymtms.settlement.pojo.GoodsbillMaster;
import com.ymtms.settlement.service.CollectingMoneyBalanceService;
import com.ymtms.settlement.util.ValidateUtil;
import com.ymtms.settlement.vo.GridRequest;
import com.ymtms.settlement.vo.GridResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/collection")
@Controller
public class CollectingMoneyBalanceController {


    @Autowired
    CollectingMoneyBalanceService collectingMoneyBalanceService;

    /*---------------------------代收结算业务------------------------------*/

    /**
     * @description: 多条件分页查询代收结算项
     * @param gridRequest 封装包含分页信息的对象（当前页、页大小、排序字段、排序规则）
     * @param goodsbillMaster 封装查询条件信息的对象
     * @param factDealDate 实际交货日期范围
     * @return: GridResult 返回符合Layui格式的查询的结果
     * @author: 邱斌雨
     * @date: 2019/10/25
     */
    @RequestMapping("/gbmlist")
    @ResponseBody
    public GridResult<GoodsbillMaster> listGbm(
            GridRequest gridRequest,
            GoodsbillMaster goodsbillMaster,
            @RequestParam(value = "factDealDate", required = false) String factDealDate){
        String startTime = "";
        String endTime = "";
        if (ValidateUtil.isNotEmpty(factDealDate)) {
            String[] split = factDealDate.split(" - ");
            startTime = split[0];
            endTime = split[1];
        }

        GridResult<GoodsbillMaster> result = collectingMoneyBalanceService.queryGbmByPage(
                gridRequest, goodsbillMaster, startTime, endTime);
        result.setCode(0);
        result.setMsg("");
        return result;
    }


    /**
     * @description: 根据gmid查询符合条件的代收结算项
     * @param gmid 货运单主表主键
     * @return: java.util.Map 符合Layui格式的json查询结果
     * @author: 邱斌雨
     * @date: 2019/11/2
     */
    @RequestMapping("/gbmDetail/{gmid}")
    @ResponseBody
    public Map gbmdetail(@PathVariable("gmid")Integer gmid){
        Map result = new HashMap();
        GoodsbillMaster goodsbillMaster = collectingMoneyBalanceService.queryGbmByGmid(gmid);
        List<GoodsbillMaster> list = new ArrayList<>();
        list.add(goodsbillMaster);
        result.put("data",list);
        result.put("count",1);
        result.put("code",0);
        result.put("msg","");
        return result;
    }


    /**
     * @description: 根据gmid查询校验并执行代收结算
     * @param collectingMoneyBalance 封装新增到代收结算表参数的对象
     * @param gmid 货运单主表表主键
     * @return: Map 包含新增操作结果的map对象
     * @author: 邱斌雨
     * @date: 2019/11/2
     */
    @RequestMapping("/add")
    @ResponseBody
    public Map add(CollectingMoneyBalance collectingMoneyBalance,
                   @RequestParam("gmid") Integer gmid){
        Map result = new HashMap();
        // 1. 对前台传来的数据进行基本验证
        if(collectingMoneyBalance == null){
            result.put("code",500);
            result.put("msg","数据传输错误");
            return result;
        }
        // 2. 执行添加和后台验证
        try {
            collectingMoneyBalanceService.save(gmid, collectingMoneyBalance);
            result.put("code",0);
            result.put("msg","结算成功");
        }catch(Exception e){
            result.put("code",500);
            result.put("msg",e.getMessage());
            return result;
        }
        return result;
    }

    /*---------------------------代收历史业务------------------------------*/

    /**
     * @description: 多条件分页查询代收结算历史
     * @param gridRequest 封装包含分页信息的类（当前页、页大小、排序字段、排序规则）
     * @param collectingMoneyBalance 包含查询条件实体类
     * @param balanceDate 结算时间范围条件
     * @return: 返回类包含实体类集合和前端layui分页条件
     * @author: 邱斌雨
     * @date: 2019/10/25
     */
    @RequestMapping("/cmblist")
    @ResponseBody
    public GridResult<CollectingMoneyBalance> listCbmHistory(
            GridRequest gridRequest, // 封装页面中laiyu表格所传过来的基本信息
            CollectingMoneyBalance collectingMoneyBalance, // 实体类接收非范围参数
            @RequestParam(value = "balanceDate", required = false) String balanceDate){
//      @RequestParam Map<String, String> params
//      可以使用实体类来实现接收其他参数
        String startTime = "";
        String endTime = "";
        if (ValidateUtil.isNotEmpty(balanceDate)) {
            String[] split = balanceDate.split(" - ");
            startTime = split[0];
            endTime = split[1];
        }
        GridResult<CollectingMoneyBalance> result = collectingMoneyBalanceService.queryCmbByPage(
                gridRequest, collectingMoneyBalance, startTime, endTime);

        result.setCode(0);
        result.setMsg("");

        return result;
    }

    /**
     * @description: 代收历史：软删除
     * @param cmsid 接收代收表主键
     * @return: 返回msg和code表示处理成功或失败
     * @author: 邱斌雨
     * @date: 2019/10/24
     */
    @RequestMapping("/delete/{cmsid}")
    @ResponseBody
    public Map RemoveByCmsid(@PathVariable("cmsid")Integer cmsid){
        Map result = new HashMap();
        try {
            collectingMoneyBalanceService.removeByCmsid(cmsid); // 删除
            // 清空指定的redis缓存
//            Set<String> key = redisTemplate.keys("goodsbillMaster::*");
//            redisTemplate.delete(key);
            result.put("code", "0");
            result.put("msg", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "500");
            result.put("msg", "删除失败");
            return result;
        }
        return result;
    }

    /**
     * @description: 代收历史：批量软删除
     * @param keys 接收代收表主键数组
     * @return: 返回msg和code表示处理成功或失败
     * @author: 邱斌雨
     * @date: 2019/10/24
     */
    @PostMapping("/batchDelete/{keys}")
    @ResponseBody
    public Map batchRemoveByCmsid(@PathVariable("keys")Integer[] keys) {
        Map result = new HashMap();
        try {
            collectingMoneyBalanceService.batchRemoveByCmsid(keys); // 批量删除
            // 清空指定的redis缓存
//            Set<String> key = redisTemplate.keys("goodsbillMaster::*");
//            redisTemplate.delete(key);
            result.put("code", "0");
            result.put("msg", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "500");
            result.put("msg", "删除失败");
            return result;
        }
        return result;
    }

    /*---------------------------代收业务变更------------------------------*/


    @RequestMapping("/changelist")
    @ResponseBody
    public GridResult<GoodsbillMaster> changelist(
            GridRequest gridRequest,
            GoodsbillMaster goodsbillMaster){
        GridResult<GoodsbillMaster> result = collectingMoneyBalanceService.queryChangeAbleGbmByPage(gridRequest, goodsbillMaster);
        result.setCode(0);
        result.setMsg("");
        return result;
    }


    @RequestMapping("/gbmchangeAbleDetail/{gmid}")
    @ResponseBody
    public Map gbmchangeAbleDetail(@PathVariable("gmid")Integer gmid){
        Map result = new HashMap();
        GoodsbillMaster goodsbillMaster = collectingMoneyBalanceService.queryChanegAbleGbmByGmid(gmid);
        List<GoodsbillMaster> list = new ArrayList<>();
        list.add(goodsbillMaster);
        result.put("data",list);
        result.put("count",1);
        result.put("code",0);
        result.put("msg","");
        return result;
    }

    @RequestMapping("/cancelBusiness/{gmid}")
    @ResponseBody
    public Map cancelBusiness(@PathVariable(value="gmid", required = true)Integer gmid){
        Map result = new HashMap();
        try {
            collectingMoneyBalanceService.cancelBusiness(gmid);
            result.put("code",0);
            result.put("msg","取消业务成功");
        }catch(Exception e){
            result.put("code",500);
            result.put("msg",e.getMessage());
            return result;
        }
        return result;
    }

    @RequestMapping("/businessAdd")
    @ResponseBody
    public Map businessAdd(GoodsbillMaster goodsbillMaster){
        Map result = new HashMap();
        // 数据校验
        if(goodsbillMaster==null || goodsbillMaster.getGmid()==null
                || goodsbillMaster.getHelpAcceptPayment()==null
                || goodsbillMaster.getSendGoodsCustomerMobile()==null){
            result.put("code",500);
            result.put("msg","数据传输错误");
            return result;
        }else {
            if(!(BigDecimal.ZERO.compareTo(goodsbillMaster.getHelpAcceptPayment())<1)){
                result.put("code",500);
                result.put("msg","货款必须大于0");
                return result;
            }
            if(goodsbillMaster.getSendGoodsCustomerMobile().equals("无业务")
                    || goodsbillMaster.getSendGoodsCustomerMobile().trim().equals("")){
                result.put("code",500);
                result.put("msg","请选择业务");
                return result;
            }
        }
        try {
            collectingMoneyBalanceService.addBusiness(goodsbillMaster);
            result.put("code",0);
            result.put("msg","添加业务成功");
        }catch(Exception e){
            result.put("code",500);
            result.put("msg",e.getMessage());
            return result;
        }
        return result;
    }

    @RequestMapping("/businessEdit")
    @ResponseBody
    public Map businessEdit(GoodsbillMaster goodsbillMaster){
        Map result = new HashMap();
        System.out.println(goodsbillMaster);
        // 数据校验
        if(goodsbillMaster==null || goodsbillMaster.getGmid()==null
                || goodsbillMaster.getSendGoodsCustomerMobile()==null){
            result.put("code",500);
            result.put("msg","数据传输错误");
            return result;
        }else {
            if(goodsbillMaster.getSendGoodsCustomerMobile().equals("无业务")
                    || goodsbillMaster.getSendGoodsCustomerMobile().trim().equals("")){
                result.put("code",500);
                result.put("msg","请选择业务");
                return result;
            }

            if(goodsbillMaster.getPayKickback()!= null && !(BigDecimal.ZERO.compareTo(goodsbillMaster.getPayKickback())<1)){
                result.put("code",500);
                result.put("msg","变更货款必须大于0");
                return result;
            }

        }
        try {
            collectingMoneyBalanceService.editBusiness(goodsbillMaster);
            result.put("code",0);
            result.put("msg","修改业务成功");
        }catch(Exception e){
            result.put("code",500);
            result.put("msg",e.getMessage());
            return result;
        }
        return result;
    }
}
